package com.chensi.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chensi.common.AjaxJson;
import com.chensi.common.Constants;
import com.chensi.common.Pager;
import com.chensi.model.Flow;
import com.chensi.service.IFlowService;
import com.chensi.util.BeanUtils;

@Controller
@RequestMapping("flow")
public class FlowController {
	
	@Autowired
	private IFlowService flowService;

	@RequestMapping("main")
	public String main() {
		return "flow/main";
	}
	
	@RequestMapping("addView")
	public ModelAndView addView() {
		return new ModelAndView("flow/edit");
	}
	
	@RequestMapping("updateView")
	public ModelAndView updateView(Flow model) {
		Flow entity = flowService.get(model.getId());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("flow", entity);
		return new ModelAndView("flow/edit", map);
	}
	
	//===================
	
	/**
	 * 获取详情
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("get.do")
	@ResponseBody
	public AjaxJson get(Integer id) {
		if (id == null) {
			return AjaxJson.getFailInfo(Constants.NOT_BLANK);
		}
		return AjaxJson.getSuccessInfo(flowService.get(id));
	}

	/**
	 * 筛选加载列表
	 * 
	 * @return
	 */
	@RequestMapping("page.do")
	@ResponseBody
	public AjaxJson page(Flow flow, Pager pager) {
		return AjaxJson.getSuccessInfo(flowService.pageByEntity(flow, pager));
	}

	/**
	 * 新增
	 * 
	 * @return
	 */
	@RequestMapping("add.do")
	@ResponseBody
	public AjaxJson add(Flow flow) {
		flowService.save(flow);
		return AjaxJson.getSuccessInfo();
	}

	/**
	 * 修改
	 * 
	 * @param flow
	 * @return
	 */
	@RequestMapping("update.do")
	@ResponseBody
	public AjaxJson update(Flow flow) {
		if (flow.getId() == null) {
			return AjaxJson.getFailInfo(Constants.NOT_BLANK);
		}
		Flow param = new Flow();
		param.setName(flow.getName());
		param.setIdNe(flow.getId());
		Flow tmp = flowService.getByEntity(param);
		if (tmp != null) {
			return AjaxJson.getFailInfo("票据名已存在");
		}
		Flow old = flowService.get(flow.getId());
		BeanUtils.copyNotNullProperties(flow, old);
		flowService.update(old);
		return AjaxJson.getSuccessInfo();
	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("remove.do")
	@ResponseBody
	public AjaxJson remove(Integer id) {
		if (id == null) {
			return AjaxJson.getFailInfo(Constants.NOT_BLANK);
		}
		flowService.remove(id);
		return AjaxJson.getSuccessInfo();
	}
}
